﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArraysAndStrings.MinSubArrayLen
{
    class MainProject
    {
        static void Main(string[] args)
        {
            int[] nums = new int[] { 1,2,3,4,5 };
            //int[] nums = new int[] { 2, 3, 1, 2, 4, 3 };
            Console.WriteLine(MinSubArrayLen(11, nums));
            Console.ReadKey();
        }
        public static int MinSubArrayLen(int target, int[] nums)
        {
            Queue<int> que = new Queue<int>();
            int sum = nums[0];
            que.Enqueue(nums[0]);
            int minLength = int.MaxValue;
            for (int i = 1; i < nums.Length; i++)
            {
                if (sum < target)
                {
                    sum += nums[i];
                    que.Enqueue(nums[i]);
                }
                else
                {
                    minLength = Math.Min(que.Count, minLength);
                    int temp = sum + nums[i];
                    while (temp >= target)
                    {
                        if (que.Count > 0 && temp - que.Peek() >= target)
                        {
                            temp -= que.Peek();
                            sum -= que.Dequeue();
                        }
                        else
                        {
                            que.Enqueue(nums[i]);
                            sum += nums[i];
                            minLength = Math.Min(que.Count, minLength);
                            break;

                        }
                    }
                }
            }
            int temp1 = sum;
            while (temp1 >= target)
            {
                if (que.Count > 0 && temp1 - que.Peek() >= target)
                {
                    temp1 -= que.Peek();
                    sum -= que.Dequeue();
                }
                else
                {
                    minLength = Math.Min(que.Count, minLength);
                    break;
                }
            }
            return minLength == int.MaxValue ? 0 : minLength;
        }
    }
}
